/**
 * 关于 openlayers 加载底图资源说明
 * 底图投影常用 墨卡托球面投影(ESPG:3857) 经纬度平面投影(ESPG:4326) [此处不确定是否描述正确]
 * 本系统采用 ESPG:4326 经纬度
 * 目前有以下几种资源：
 * XYZ
 * WMS
 * WMTS
 * WFS
 */

/**
 * 关于天地图服务资源
 * 天地图，百度地图，高德地图，必应地图
 * 省界
 * 注记
 * 所有服务列表 https://service.tianditu.gov.cn/#/
 * 常用 WMTS 服务列表 http://lbs.tianditu.gov.cn/server/MapService.html
 */
import { BASEMAP_GALLERY } from './basemap-gallery';
import { getBDImgSource, getBDVecSource } from './transform-baidu';

/**
 * 此处只放置 openlayers api 资源
 */
import TileLayer from 'ol/layer/Tile';
import { XYZ, TileWMS, TileImage, WMTS, BingMaps } from 'ol/source';
import WMTSTileGrid from 'ol/tilegrid/WMTS';
import { get as getProjection } from 'ol/proj';
import { getTopLeft, getWidth } from 'ol/extent';

export const basemap_catch = {}; // 缓存底图，避免重复构造
let lastKey = null; // 表示上次底图，切换时关闭上次底图

export function addBasemapByKey(olmap, key) {
	if (lastKey && lastKey !== key) {
		basemap_catch[lastKey].setVisible(false);
	}

	if (basemap_catch[key]) {
		basemap_catch[key].setVisible(true);
	} else {
		let layer = getLayerByKey(key);
		basemap_catch[key] = layer;
		olmap.addLayer(layer);
	}
	lastKey = key;
}

function getLayerByKey(key) {
	let layer = null;
	if (key.match(/(bd)/i)) {
		layer = getXYZLayer(key);
	} else if (key.match(/(tdt)/i)) {
		layer = getWMTSLayerByConfig(BASEMAP_GALLERY[key]);
	} else if (key === 'BingImg') {
		layer = getBingLayer();
	}
	return layer;
}

// 参考 https://openlayers.org/en/latest/examples/wmts.html
function getWMTSLayerByConfig(config) {
	const projection = getProjection('EPSG:4326');
	const projectionExtent = projection.getExtent();
	const size = getWidth(projectionExtent) / 256;
	const resolutions = new Array(19);
	const matrixIds = new Array(19);
	for (let z = 0; z < 19; ++z) {
		// generate resolutions and matrixIds arrays for this WMTS
		resolutions[z] = size / Math.pow(2, z);
		matrixIds[z] = z;
	}

	// arcgisonline 服务资源 https://services.arcgisonline.com/arcgis/rest/services

	return new TileLayer({
		source: new WMTS({
			url: config.url,
			layer: config.layer,
			style: 'default',
			wrapX: true,
			matrixSet: config.matrixSet,
			format: 'tiles',
			projection: projection,
			tileGrid: new WMTSTileGrid({
				origin: getTopLeft(projectionExtent),
				resolutions: resolutions,
				matrixIds: matrixIds,
			}),
		}),
	});
}

// 天地图 xyz 资源
// 参考 https://openlayers.org/en/latest/examples/xyz.html
function getXYZLayer(key) {
	let source = null;

	// let layerXYZ = new TileLayer({
	// 	source: new XYZ({
	// 		url: 'http://t{0-7}.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=9a54b78c22759bf1521ca4cba8bea124',
	// 	}),
	// });

	switch (key) {
		case 'BdVec':
			source = getBDVecSource();
			break;
		case 'BdImg':
			source = getBDImgSource();
			break;
	}

	return new TileLayer({
		source: source,
	});
}

// 开发时使用此地图
function getBingLayer() {
	return new TileLayer({
		source: new BingMaps({
			key: 'AhRJ4_eMUIgdPPJganNuN3d4yU4Hut1kTB4eKoHxNKIRwpJy5KNjD4N3Sy_KEzt-',
			imagerySet: 'Aerial',
			// use maxZoom 19 to see stretched tiles instead of the BingMaps
			// "no photos at this zoom level" tiles
			// maxZoom: 19
		}),
	});
}

// 参考 https://openlayers.org/en/latest/examples/wms-tiled.html
// function getWMSLayer() {
// 	return new TileLayer({
// 		extent: [-13884991, 2870341, -7455066, 6338219],
// 		source: new TileWMS({
// 			url: 'http://gisserver.tianditu.gov.cn/TDTService/wfs?tk=9a54b78c22759bf1521ca4cba8bea124',
// 			params: { LAYERS: 'LRRL，LRDL', TILED: true },
// 			serverType: 'geoserver',
// 			// Countries have transparency, so do not fade tiles:
// 			transition: 0,
// 		}),
// 	});
// }
